<?php

namespace app\common\service\ai;

use app\common\service\member\MemberService;
use app\common\service\system\UserService;
use think\facade\Db;
use app\common\service\CommonService;

/**
 * 订单
 */
class BillService extends CommonService {

    /**
     * 表名
     * @static string
     */
    protected static $table = 'bill';

    /**
     * 创建账单号
     * @param string $prefix 前缀
     * @return array
     */
    public static function createBill($data) {
        $billNo =  "B" . date('YmdHis') . getRandomString('numeric', 6);
        Db::startTrans();

        $user = MemberService::info($data['member_id'], true, true, true);
        $sale_price = self::query('order')->where(['order_no' => $data['order_no']])->_value('sale_price');


        $order = OrderService::getDetail($data["order_no"]);
        PromoterService::createCommission([$data["order_no"],$order['member_id'],$user['share_id']]);

        if(!$sale_price){
            Db::rollback();
            exception('订单不存在');
        }

        $data = [
            'member_id' => $data['member_id'],
            'bill_no' => $billNo,
            'order_no' => $data["order_no"],
            'sale_price' => $sale_price,
        ];
        $bill_id = self::model()->_insert("bill", $data);

        if (!$bill_id) {
            Db::rollback();
            exception();
        }

        Db::commit();
        $data = WxPayService::GetPayParam($user["openid"], $sale_price,$billNo);
        return $data;
    }

    /**
     * 创建账单号
     * @param string $prefix 前缀
     * @return array
     */
    public static function saveBill($data) {
        self::model()->_update('bill', $data, ['bill_no' => $data["bill_no"]]);
        return $data;
    }

    /**
     * 列表
     * @param array $data 数据
     * @return array
     */
    public static function getList($data) {
        $list = self::query(self::$table)->_equal('member_id')->order('id desc')->_page();
        return $list;
    }

    /**
     * 详情
     * @param array $data 数据
     * @return array
     */
    public static function getDetail($billNo) {
        return self::query(self::$table)->where(['bill_no' => $billNo])->_find();
    }

}
